﻿using ECO.Admin.Core.Attribute;
using ECO.Admin.Core.EventBus;
using ECO.Admin.Core.Sugar;
using ECO.Admin.Web.Core.Handlers;
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Profiling.Internal;
using StackExchange.Redis;

namespace ECO.Admin.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped(typeof(Repository<>));
            services.AddSqlsugarSetup(App.Configuration);
            services.AddConsoleFormatter();
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);
            services.AddEventBus(options =>
            {
                options.AddSubscriber(typeof(EventSubscriber));
                //var redisIP = App.Configuration["Redis:IP"];
                //if (!string.IsNullOrWhiteSpace(redisIP))
                //{
                //    // 创建 Redis 连接对象
                //    var connectionMultiplexer = ConnectionMultiplexer.Connect(redisIP);

                //    // 创建默认内存通道事件源对象，可自定义队列路由key，比如这里是 eventbus
                //    var redisEventSourceStorer = new RedisEventSourceStorer(connectionMultiplexer, "eventbus", 3000);

                //    // 替换默认事件总线存储器
                //    options.ReplaceStorer(serviceProvider =>
                //    {
                //        return redisEventSourceStorer;
                //    });
                //}
          
            });
            //services.AddStackExchangeRedisCache(x => x.ConfigurationOptions = new ConfigurationOptions
            //{
            //    EndPoints = { App.Configuration["Redis:IP"] }, // 设置 Redis 服务器地址和端口

            //    AbortOnConnectFail = true, // 连接失败时是否抛出异常
            //    ConnectTimeout = 5000, // 连接超时时间（毫秒）
            //    SyncTimeout = 5000 // 同步操作超时时间（毫秒）
            //});
            services.AddCorsAccessor();
            services.AddControllers(options =>
                    {
                        options.Filters.Add<ExceptionAttribute>();
                    })
                    .AddInjectWithUnifyResult();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}